package com.fengye.security.custom.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fengye.common.constants.AppHttpCodeEnum;
import com.fengye.common.exception.BusinessException;
import com.fengye.common.domain.entity.User;
import com.fengye.security.mapper.UserMapper;
import com.fengye.security.custom.model.LoginUserDetails;
//import com.kld.quban.mapper.MenuMapper;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import jakarta.annotation.Resource;
import java.util.ArrayList;
import java.util.Objects;

/**
 * @author sunlei
 * @version 1.0
 * @date 2023/9/8 16:36:12
 * @description 自定义实现Spring Security的UserDetailService接口，【注意】此处抛出的异常可以被自定义的全局异常处理器捕获
 */
@Transactional(rollbackFor = {Exception.class, Error.class})
@Service
public class CustomUserDetailsService implements UserDetailsService {

    @Resource
    private UserMapper userMapper;

//    @Autowired
//    private MenuMapper menuMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 查询用户信息
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername, username);
        User user = userMapper.selectOne(queryWrapper);
        // 如果没有查询到用户就抛出异常
        if (Objects.isNull(user)) {
            throw new BusinessException(AppHttpCodeEnum.USER_NOT_FOUND);
        } else if ("1".equals(user.getDelFlag())) {
            throw new BusinessException(AppHttpCodeEnum.USER_IS_DELETED);
        }

        // 查询对应的【用户信息】和【权限信息】，并封装到UserDetails里面
//        List<String> perms = menuMapper.selectPermsByUid(user.getId());

        return new LoginUserDetails(user, new ArrayList<>());
    }
}
